const { Controller } = require('egg');
const WechatPay = require('wechatpay-node-v3');
const fs = require("node:fs");
const path = require("node:path");
const log4js = require('log4js');
class VipController extends Controller {

    /**
     * 支付校验接口，根据订单号，校验支付状态。
     */
    async payCheck() {
        const {ctx, app} = this;
        const {id} = ctx.request.body;
        const order = await app.mysql.get('orders', {id});
        if (order.is_pay === 1) {
            ctx.body = {
                success: true,
                data: {
                    is_pay: 1
                }
            }
        }else{
            ctx.body = {
                success: true,
                data: {
                    is_pay: 0
                }
            }
        }
    }

    /**
     * @name 微信支付回调
     * @api {post} /vip/pay 支付
     * {
     *      "id": "EV-2018022511223320873",
     *     "create_time": "2015-05-20T13:29:35+08:00",
     *     "resource_type": "encrypt-resource",
     *     "event_type": "TRANSACTION.SUCCESS",
     *     "summary": "支付成功",
     *     "resource": {
     *         "original_type": "transaction",
     *         "algorithm": "AEAD_AES_256_GCM",
     *         "ciphertext": "",
     *         "associated_data": "",
     *         "nonce": ""
     *     }
     * }
     * @returns {Promise<void>}
     */
    async notify(){
        const {ctx, app} = this;
        const {resource} = ctx.request.body;
        console.log(ctx.request.body)

            const {ciphertext, associated_data, nonce} = resource;

            // 确保从配置文件中正确读取微信支付相关参数
            const {appid, mchid, notify_url,v3_key} = app.config.wechat;
            const publicKey = fs.readFileSync(path.resolve(__dirname, './../../certs/apiclient_cert.pem'));
            const privateKey = fs.readFileSync(path.resolve(__dirname, './../../certs/apiclient_key.pem'));
            const wechatPay = new WechatPay(appid, mchid, publicKey, privateKey);

            // 解密微信支付回调数据
            const decryptRes = await wechatPay.decipher_gcm(ciphertext, associated_data, nonce,v3_key);


            // 提取解密后的订单信息
            const {id, amount, attach, create_time, event_type, summary, resource_type} = decryptRes;
            const {id: orderId} = JSON.parse(attach);

            // 查询订单信息
            const order = await app.mysql.get('orders', {id: orderId});


            // 如果订单已支付，直接返回成功响应
            if (order.is_pay === 1) {
                ctx.body = {
                    code: "SUCCESS",
                    message: '订单已支付'
                };
                return;
            }

            // 更新订单状态为已支付
            await app.mysql.update('orders', {id: orderId, is_pay: 1, pay_time: new Date()});
            let dateTime = new Date();
            // 更新用户信息，设置会员与会员时间
            switch (order.vip_type){
                case 'month':
                    dateTime = new Date(new Date().getTime() + 30 * 24 * 60 * 60 * 1000)
                    break;
                case 'year':
                    dateTime = new Date(new Date().getTime() + 365 * 24 * 60 * 60 * 1000)
                    break;
            }
            // 计算到期时间：当前时间 + vipType.days


            const vip_expire_time = dateTime;

            await app.mysql.update('users', {id: order.user_id, vip_type: order.vip_type, vip_expire_time: vip_expire_time});
            await app.mysql.insert('users_vip', {
                user_id: order.user_id,
                type: order.vip_type,
                end_time: vip_expire_time,
                start_time: new Date(),
                amount: amount.total,
                order_id:order.id,
            });

            // 返回成功响应
            ctx.body = {
                code: "SUCCESS",
                message: '支付成功'
            };

    }
    async pay() {
        const {ctx, app} = this;


        const openid = ctx.currentUser.wx_opneid;
        const {vip_type} = ctx.request.body;
        const {appid, mchid,notify_url} = app.config.wechat;
        const publicKey = fs.readFileSync(path.resolve(__dirname, './../../certs/apiclient_cert.pem'));
        const privateKey = fs.readFileSync(path.resolve(__dirname, './../../certs/apiclient_key.pem'));
        const wechatPay = new WechatPay(appid, mchid, publicKey, privateKey);
        console.log(vip_type)
        const vipType =  app.config.vipTypes.find((item) => item.type === vip_type);
        console.log(vipType)
        const amount = vipType.price;
        const insertRes =  await app.mysql.insert('orders', {
            user_id: ctx.currentUser.id,
            amount: amount * 100,
            is_pay: 0,
            create_time: new Date(),
            vip_type: vip_type
        });
        const insertId = insertRes.insertId;
        const res = await wechatPay.transactions_jsapi({
            out_trade_no: Date.now().toString()  +  insertId,
            appid,
            mchid,
            attach:'{"id":"'+insertId+'"}',
            description: '开通会员：' + vipType.name,
            notify_url: 'https://ysdai.m3it.cn/api/vip/notify',
            amount: {
                total: amount * 100
            },
            payer: {
                openid
            }
        })
        if(res.status === 200){
            ctx.body = {
                success:true,
                data: res.data
            }
        }else{
            console.error(res.error);
            ctx.body = {
                success:false,
                data: res.data
            }
        }
    }
}
module.exports = VipController;